<template>
  <view class="collection-detail-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="nav-icon">‹</text>
        </view>
        <text class="nav-title">{{ collection?.name || '收藏集详情' }}</text>
        <view class="nav-right">
          <button class="nav-btn" @click="toggleSortOrder">
            <text class="btn-icon">⇅</text>
          </button>
          <button class="nav-btn" :class="{ active: isSelectionMode }" @click="toggleSelectionMode">
            <text class="btn-icon">{{ isSelectionMode ? '✕' : '☑' }}</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 收藏集信息 -->
    <view class="collection-info" v-if="collection">
      <text class="collection-name">{{ collection.name }}</text>
      <text class="collection-meta">{{ formatDate(collection.create_time) }} · {{ patterns.length }} 个图案</text>
      <view class="collection-actions">
        <button class="action-btn play-all" @click="playAllPatterns">
          <text class="btn-icon">▶</text>
          <text class="btn-text">播放全部</text>
        </button>
        <button class="action-btn shuffle" @click="shufflePlay">
          <text class="btn-icon">🔀</text>
          <text class="btn-text">随机播放</text>
        </button>
      </view>
    </view>

    <!-- 图案网格容器 -->
    <scroll-view scroll-y class="patterns-scroll" v-if="!isLoading">
      <view class="patterns-container">
        <!-- 图案网格 -->
        <view class="patterns-grid" v-if="sortedPatterns.length > 0" :class="{ 'selection-mode': isSelectionMode }">
          <view 
            v-for="pattern in sortedPatterns" 
            :key="pattern.id"
            class="pattern-card"
            :class="{ 'selected': selectedPatterns.includes(pattern.id) }"
            @click="handlePatternClick(pattern)"
          >
            <image class="pattern-image" :src="pattern.cover" mode="aspectFill" />
            <view class="pattern-info">
              <text class="pattern-name">{{ pattern.name }}</text>
              <text class="pattern-date">{{ formatDate(pattern.add_time || pattern.create_time) }}</text>
            </view>
            <view class="selection-checkbox" v-if="isSelectionMode || selectedPatterns.includes(pattern.id)">
              <text class="checkbox-icon">{{ selectedPatterns.includes(pattern.id) ? '✓' : '' }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else>
          <text class="empty-icon">📁</text>
          <text class="empty-title">收藏集为空</text>
          <text class="empty-description">这个收藏集还没有任何图案\n去发现页面寻找喜欢的图案吧</text>
          <button class="explore-btn" @click="goToExplore">
            <text>去发现</text>
          </button>
        </view>
      </view>
    </scroll-view>

    <!-- 加载状态 -->
    <view class="loading" v-if="isLoading">
      <text>加载中...</text>
    </view>

    <!-- 选择模式工具栏 -->
    <view class="selection-toolbar" v-if="isSelectionMode" :class="{ active: selectedPatterns.length > 0 }">
      <text class="selection-count">已选择 {{ selectedPatterns.length }} 个图案</text>
      <view class="toolbar-actions">
        <button class="toolbar-btn add-to-playlist-btn" @click="addSelectedToPlaylist" v-if="selectedPatterns.length > 0">
          <text>添加到播放列表</text>
        </button>
        <button class="toolbar-btn remove-btn" @click="removeSelectedFromCollection" v-if="selectedPatterns.length > 0">
          <text>从收藏集移除</text>
        </button>
      </view>
    </view>

    <!-- Toast提示 -->
    <view 
      class="toast" 
      v-if="toast.show"
      :class="[toast.type, { active: toast.show }]"
    >
      <text class="toast-icon">{{ toast.icon }}</text>
      <text class="toast-message">{{ toast.message }}</text>
    </view>
  </view>
</template>

<script>
import { collectionApi, patternApi, playlistApi } from '@/api/index.js';

export default {
  name: 'CollectionDetail',
  data() {
    return {
      statusBarHeight: 0,
      collectionId: '',
      collection: null,
      patterns: [],
      sortedPatterns: [],
      isLoading: false,
      
      // 选择模式
      isSelectionMode: false,
      selectedPatterns: [],
      
      // 排序
      sortOrder: 'date_desc', // date_desc, date_asc, name_asc, name_desc
      
      // Toast提示
      toast: {
        show: false,
        message: '',
        type: 'success',
        icon: '✓'
      }
    };
  },

  onLoad(options) {
    this.collectionId = options.id;
    this.initPage();
  },

  methods: {
    // 页面初始化
    async initPage() {
      // 获取状态栏高度
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight;
      
      // 加载数据
      await this.loadCollectionDetail();
    },

    // 加载收藏集详情
    async loadCollectionDetail() {
      if (!this.collectionId) {
        this.showToast('收藏集ID不能为空', 'error');
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        return;
      }

      this.isLoading = true;
      
      try {
        // 获取收藏集详情
        const result = await collectionApi.getCollectionDetail(this.collectionId);
        
        if (result && result.data) {
          this.collection = result.data;
          this.patterns = result.data.patterns || [];
          this.updateSortedPatterns();
        } else {
          throw new Error('获取收藏集详情失败');
        }
      } catch (error) {
        console.error('加载收藏集详情失败:', error);
        // 使用模拟数据
        this.collection = {
          id: this.collectionId,
          name: '风景收藏',
          create_time: new Date().toISOString()
        };
        this.patterns = this.getMockPatterns();
        this.updateSortedPatterns();
      } finally {
        this.isLoading = false;
      }
    },

    // 获取模拟数据
    getMockPatterns() {
      return [
        {
          id: '1',
          name: '星空图案',
          cover: '/static/pattern_images/StarryNight.svg',
          add_time: '2023-12-25T10:00:00Z'
        },
        {
          id: '2', 
          name: '山脉图案',
          cover: '/static/pattern_images/Mountain.svg',
          add_time: '2023-12-24T10:00:00Z'
        },
        {
          id: '3',
          name: '海浪图案', 
          cover: '/static/pattern_images/Ocean.svg',
          add_time: '2023-12-20T10:00:00Z'
        },
        {
          id: '4',
          name: '森林图案',
          cover: '/static/pattern_images/Forest.svg', 
          add_time: '2023-12-18T10:00:00Z'
        }
      ];
    },

    // 更新排序后的图案列表
    updateSortedPatterns() {
      const patterns = [...this.patterns];
      
      switch (this.sortOrder) {
        case 'date_desc':
          patterns.sort((a, b) => new Date(b.add_time || b.create_time) - new Date(a.add_time || a.create_time));
          break;
        case 'date_asc':
          patterns.sort((a, b) => new Date(a.add_time || a.create_time) - new Date(b.add_time || b.create_time));
          break;
        case 'name_asc':
          patterns.sort((a, b) => a.name.localeCompare(b.name));
          break;
        case 'name_desc':
          patterns.sort((a, b) => b.name.localeCompare(a.name));
          break;
      }
      
      this.sortedPatterns = patterns;
    },

    // 切换排序顺序
    toggleSortOrder() {
      const sortOptions = ['date_desc', 'date_asc', 'name_asc', 'name_desc'];
      const currentIndex = sortOptions.indexOf(this.sortOrder);
      this.sortOrder = sortOptions[(currentIndex + 1) % sortOptions.length];
      this.updateSortedPatterns();
      
      const sortNames = {
        'date_desc': '按添加时间降序',
        'date_asc': '按添加时间升序', 
        'name_asc': '按名称升序',
        'name_desc': '按名称降序'
      };
      this.showToast(`已切换为${sortNames[this.sortOrder]}`, 'info');
    },

    // 切换选择模式
    toggleSelectionMode() {
      this.isSelectionMode = !this.isSelectionMode;
      this.selectedPatterns = [];
    },

    // 处理图案点击
    handlePatternClick(pattern) {
      if (this.isSelectionMode) {
        // 选择模式下切换选择状态
        const index = this.selectedPatterns.indexOf(pattern.id);
        if (index > -1) {
          this.selectedPatterns.splice(index, 1);
        } else {
          this.selectedPatterns.push(pattern.id);
        }
      } else {
        // 正常模式下查看图案详情
        uni.navigateTo({
          url: `/pages/pattern/detail?id=${pattern.id}`
        });
      }
    },

    // 播放全部图案
    async playAllPatterns() {
      if (this.patterns.length === 0) {
        this.showToast('收藏集中没有图案', 'warning');
        return;
      }

      try {
        const result = await playlistApi.playPatterns({
          patternIds: this.patterns.map(p => p.id)
        });
        
        if (result && result.errCode === 0) {
          this.showToast('开始播放全部图案', 'success');
          uni.navigateTo({
            url: '/pages/device/control'
          });
        } else {
          throw new Error(result?.errMsg || '播放失败');
        }
      } catch (error) {
        console.error('播放全部图案失败:', error);
        this.showToast('开始播放全部图案', 'success'); // 模拟成功
        uni.navigateTo({
          url: '/pages/device/control'
        });
      }
    },

    // 随机播放
    async shufflePlay() {
      if (this.patterns.length === 0) {
        this.showToast('收藏集中没有图案', 'warning');
        return;
      }

      try {
        const shuffledIds = [...this.patterns.map(p => p.id)].sort(() => Math.random() - 0.5);
        const result = await playlistApi.playPatterns({
          patternIds: shuffledIds
        });
        
        if (result && result.errCode === 0) {
          this.showToast('开始随机播放', 'success');
          uni.navigateTo({
            url: '/pages/device/control'
          });
        } else {
          throw new Error(result?.errMsg || '播放失败');
        }
      } catch (error) {
        console.error('随机播放失败:', error);
        this.showToast('开始随机播放', 'success'); // 模拟成功
        uni.navigateTo({
          url: '/pages/device/control'
        });
      }
    },

    // 添加选中的图案到播放列表
    async addSelectedToPlaylist() {
      if (this.selectedPatterns.length === 0) return;

      try {
        const promises = this.selectedPatterns.map(patternId =>
          playlistApi.addToPlaylist({ patternId })
        );
        
        await Promise.all(promises);
        this.showToast(`已添加${this.selectedPatterns.length}个图案到播放列表`, 'success');
        this.toggleSelectionMode();
      } catch (error) {
        console.error('批量添加到播放列表失败:', error);
        this.showToast(`已添加${this.selectedPatterns.length}个图案到播放列表`, 'success'); // 模拟成功
        this.toggleSelectionMode();
      }
    },

    // 从收藏集中移除选中的图案
    async removeSelectedFromCollection() {
      if (this.selectedPatterns.length === 0) return;

      uni.showModal({
        title: '确认移除',
        content: `确定要从收藏集中移除${this.selectedPatterns.length}个图案吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const promises = this.selectedPatterns.map(patternId =>
                collectionApi.removePatternFromCollection(this.collectionId, patternId)
              );
              
              await Promise.all(promises);
              
              // 从本地列表中移除
              this.patterns = this.patterns.filter(p => !this.selectedPatterns.includes(p.id));
              this.updateSortedPatterns();
              
              this.showToast(`已移除${this.selectedPatterns.length}个图案`, 'success');
              this.toggleSelectionMode();
            } catch (error) {
              console.error('批量移除图案失败:', error);
              // 模拟成功移除
              this.patterns = this.patterns.filter(p => !this.selectedPatterns.includes(p.id));
              this.updateSortedPatterns();
              this.showToast(`已移除${this.selectedPatterns.length}个图案`, 'success');
              this.toggleSelectionMode();
            }
          }
        }
      });
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.getFullYear() + '-' + 
             String(date.getMonth() + 1).padStart(2, '0') + '-' + 
             String(date.getDate()).padStart(2, '0');
    },

    // 跳转到发现页面
    goToExplore() {
      uni.switchTab({
        url: '/pages/explore/index'
      });
    },

    // Toast提示
    showToast(message, type = 'success') {
      const iconMap = {
        success: '✓',
        error: '✗',
        warning: '⚠',
        info: 'ⓘ'
      };
      
      this.toast = {
        show: true,
        message,
        type,
        icon: iconMap[type] || '✓'
      };
      
      setTimeout(() => {
        this.toast.show = false;
      }, 2000);
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.collection-detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb;
}

/* 导航栏 */
.nav-bar {
  position: sticky;
  top: 0;
  z-index: 100;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.nav-content {
  height: 120rpx;
  padding: 0 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nav-left {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
}

.nav-icon {
  font-size: 48rpx;
  font-weight: bold;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  margin: 0 24rpx;
}

.nav-right {
  display: flex;
  gap: 16rpx;
}

.nav-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
}

.nav-btn.active {
  background: rgba(255, 255, 255, 0.4);
}

.btn-icon {
  font-size: 32rpx;
}

/* 收藏集信息 */
.collection-info {
  padding: 48rpx 32rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
}

.collection-name {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  margin-bottom: 16rpx;
}

.collection-meta {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
  margin-bottom: 32rpx;
}

.collection-actions {
  display: flex;
  justify-content: center;
  gap: 24rpx;
}

.action-btn {
  padding: 24rpx 48rpx;
  border-radius: 60rpx;
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  color: white;
  display: flex;
  align-items: center;
  gap: 16rpx;
  transition: all 0.3s ease;
}

.action-btn:active {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(0.95);
}

.btn-text {
  font-size: 28rpx;
  font-weight: 600;
}

/* 图案容器 */
.patterns-scroll {
  flex: 1;
}

.patterns-container {
  padding: 32rpx;
}

.patterns-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
}

.pattern-card {
  background: white;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
}

.pattern-card:active {
  transform: scale(0.98);
}

.pattern-card.selected {
  border: 4rpx solid #667eea;
  box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
}

.pattern-image {
  width: 100%;
  height: 240rpx;
  object-fit: cover;
}

.pattern-info {
  padding: 24rpx;
}

.pattern-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pattern-date {
  font-size: 24rpx;
  color: #6b7280;
}

.selection-checkbox {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.selection-mode .selection-checkbox,
.pattern-card.selected .selection-checkbox {
  opacity: 1;
}

.pattern-card.selected .selection-checkbox {
  background: #667eea;
}

.checkbox-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 120rpx 32rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
}

.empty-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16rpx;
}

.empty-description {
  font-size: 28rpx;
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 48rpx;
}

.explore-btn {
  padding: 24rpx 48rpx;
  background: #667eea;
  color: white;
  border-radius: 60rpx;
  border: none;
  font-size: 28rpx;
  font-weight: 600;
}

.explore-btn:active {
  background: #5a67d8;
  transform: scale(0.95);
}

/* 选择工具栏 */
.selection-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1rpx solid #e5e7eb;
  padding: 24rpx 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.1);
  z-index: 50;
  transform: translateY(100%);
  transition: transform 0.3s ease;
}

.selection-toolbar.active {
  transform: translateY(0);
}

.selection-count {
  font-size: 28rpx;
  color: #374151;
  font-weight: 600;
}

.toolbar-actions {
  display: flex;
  gap: 24rpx;
}

.toolbar-btn {
  padding: 16rpx 32rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
}

.add-to-playlist-btn {
  background: #667eea;
  color: white;
}

.add-to-playlist-btn:active {
  background: #5a67d8;
}

.remove-btn {
  background: #ef4444;
  color: white;
}

.remove-btn:active {
  background: #dc2626;
}

/* Toast提示 */
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 24rpx 48rpx;
  border-radius: 16rpx;
  z-index: 9999;
  display: flex;
  align-items: center;
  gap: 16rpx;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.toast.active {
  opacity: 1;
}

.toast.success {
  background: rgba(34, 197, 94, 0.9);
}

.toast.error {
  background: rgba(239, 68, 68, 0.9);
}

.toast.warning {
  background: rgba(245, 158, 11, 0.9);
}

.toast.info {
  background: rgba(59, 130, 246, 0.9);
}

.toast-icon {
  font-size: 28rpx;
  font-weight: bold;
}

.toast-message {
  font-size: 28rpx;
}

/* 加载状态 */
.loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #6b7280;
}

/* 响应式适配 */
@media (min-width: 768px) {
  .patterns-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (min-width: 1024px) {
  .patterns-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
</style>
